//
//  HomeViewController.swift
//  ams
//
//  Created by coterjiesen on 2017/4/26.
//  Copyright © 2017年 coterjiesen. All rights reserved.
//

import UIKit
import MJRefresh
import Alamofire


let kHomeTab = "me.fin.homeTab"

class HomeViewController: UIViewController {
    let closeHeight: CGFloat = 73
    let openHeight: CGFloat = 166
    var itemHeight = [CGFloat](repeating: 73.0, count: 3)
    
    var tab:String? = nil
    // 登录次数
    var loginTimesLabel: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        label.text = "登录次数:"
        return label;
    }()
    // 登录次数
    var loginTimesLabel_v: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        return label;
    }()
    // 上次登录ip
    var lastIpLabel: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        label.text = "上次登录地址:"
        return label;
    }()
    // 上次登录ip
    var lastIpLabel_v: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        return label;
    }()
    // 上次登录时间
    var lastLoginTimeLabel: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        label.text = "上次登录时间:"
        return label;
    }()
    // 上次登录时间
    var lastLoginTimeLabel_v: UILabel = {
        let label = UILabel()
        label.font = v2Font(14)
        return label;
    }()


    fileprivate var _tableView :UITableView!
    fileprivate var tableView: UITableView {
        get{
            if(_tableView != nil){
                return _tableView!;
            }
            _tableView = UITableView();
            _tableView.separatorStyle = UITableViewCellSeparatorStyle.none;
            
            regClass(_tableView, cell: HomeTableViewCell.self);
            regClass(self.tableView, cell: MenuViewCell.self)
            regClass(self.tableView, cell: BinInfoViewCell.self)
            regClass(self.tableView, cell: ScrollViewCell.self)
            
            _tableView.backgroundColor = UIColor(patternImage: UIImage(named:"background.png")!)
            
            _tableView.delegate = self
            _tableView.dataSource = self
            return _tableView!;
            
        }
    }

    /// 装上面定义的那些元素的容器
//    var footer:UIView = UIView(frame:CGRect(x:0, y:0, width:SCREEN_WIDTH, height:50))
    var content:UIView = UIView()


    override func viewWillAppear(_ animated: Bool) {
        CuClient.sharedInstance.drawerController?.openDrawerGestureModeMask = .panningCenterView
    }
    override func viewDidAppear(_ animated: Bool) {
        self.loadingData()
        
        //刷新数据
        self.tableView.reloadData()
    }

    override func viewWillDisappear(_ animated: Bool) {
        CuClient.sharedInstance.drawerController?.openDrawerGestureModeMask = []
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title="资产管理系统";
//        self.tab = CuSettings.sharedInstance[kHomeTab]
//        self.setupNavigationItem()
        self.setup()
        
//        checkLogin()
//        buttonOutBin.addTarget(self, action: #selector(HomeViewController.outBinClick), for: .touchUpInside)
//        buttonErrorBin.addTarget(self, action: #selector(HomeViewController.errorBinClick), for: .touchUpInside)
        //监听程序即将进入前台运行、进入后台休眠 事 件
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.applicationWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.applicationDidEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
    }
    func setupNavigationItem(){
        let leftButton = NotificationMenuButton()
        leftButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        leftButton.addTarget(self, action: #selector(HomeViewController.leftClick), for: .touchUpInside)
        
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        rightButton.contentMode = .center
        rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -15)
        rightButton.setImage(UIImage.imageUsedTemplateMode("ic_more_horiz_36pt")!.withRenderingMode(.alwaysTemplate), for: UIControlState())
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        rightButton.addTarget(self, action: #selector(HomeViewController.rightClick), for: .touchUpInside)
    }
    func leftClick(){
        CuClient.sharedInstance.drawerController?.toggleLeftDrawerSide(animated: true, completion: nil)
    }
    func rightClick(){
        let menuArray = [KxMenuItem.init("扫一扫",image: UIImage(named: "ic_richScan"),target: self,action: #selector(clickMenu))]
        
        /*设置菜单字体*/
        KxMenu.setTitleFont(UIFont(name: "HelveticaNeue-Bold", size: 15))
         let options = OptionalConfiguration(arrowSize: 9,  //指示箭头大小
            marginXSpacing: 7,  //MenuItem左右边距
            marginYSpacing: 9,  //MenuItem上下边距
            intervalSpacing: 25,  //MenuItemImage与MenuItemTitle的间距
            menuCornerRadius: 6.5,  //菜单圆角半径
            maskToBackground: true,  //是否添加覆盖在原View上的半透明遮罩
            shadowOfMenu: false,  //是否添加菜单阴影
            hasSeperatorLine: true,  //是否设置分割线
            seperatorLineHasInsets: false,  //是否在分割线两侧留下Insets
            textColor: Color(R: 0, G: 0, B: 0),  //menuItem字体颜色
            menuBackgroundColor: Color(R: 1, G: 1, B: 1)  //菜单的底色
            
        )
        
        /*菜单位置*/
        let a = CGRect(x: self.view.frame.width-27, y: 70, width: 0, height: 0)
        KxMenu.show(in: self.view, from: a, menuItems: menuArray, withOptions: options)

    }

    func  outBinClick(){
        let vc = OutBinViewController();
        CuClient.sharedInstance.centerViewController!.navigationController?.pushViewController(vc, animated: true);
    }
    func  errorBinClick(){
        let vc = ErrorBinViewController();
        CuClient.sharedInstance.centerViewController!.navigationController?.pushViewController(vc, animated: true);
    }
    static var lastLeaveTime = Date()
    func applicationWillEnterForeground(){
        //计算上次离开的时间与当前时间差
        //如果超过2分钟，则自动刷新本页面。
        let interval = -1 * HomeViewController.lastLeaveTime.timeIntervalSinceNow
        if interval > 120 {
          //  self.tableView.mj_header.beginRefreshing()
        }
    }
    func applicationDidEnterBackground(){
        HomeViewController.lastLeaveTime = Date()
    }
}

extension HomeViewController{
    func checkLogin(){
        print("home页登录检测")
        self.kvoController.observe(CuUser.sharedInstance, keyPath: "isCheckLogin", options: [.initial , .new]){
            (observe, observer, change) -> Void in
            print("home login检测")
            if false == CuUser.sharedInstance.isLogin{
                    let loginViewController = LoginViewController()
                    CuClient.sharedInstance.centerViewController!.navigationController?.present(loginViewController, animated: true, completion: nil);
            }
        }
    }
    func loadingData(){
        Alamofire.request(AMSURL + "main/showIndexOInfo", method:.post, headers: MOBILE_CLIENT_HEADERS).validate().responseJSON { (response) -> Void in
            switch response.result {
            case .success(let value):
                print("info:\n\(value)")
            case .failure(let error):
                print("error:\(error)")
            }
        }
        lastIpLabel_v.text = CuUser.sharedInstance.user?.ip
        loginTimesLabel_v.text = CuUser.sharedInstance.user?.Countlogin
        lastLoginTimeLabel_v.text = CuUser.sharedInstance.user?.admintime
    }
    //菜单按钮点击事件
    func clickMenu(_ sender: AnyObject){
        let vc = ScanViewController();
        var style = LBXScanViewStyle()
        style.animationImage = UIImage(named: "qrcode_scan_light_green")
        vc.scanStyle = style
        CuClient.sharedInstance.centerViewController!.navigationController?.pushViewController(vc, animated: true);
    }
}
extension HomeViewController{
    func setup(){
        self.view.addSubview(tableView);
        self.setupLayout()
        self.thmemChangedHandler = {[weak self] (style) -> Void in
            self?.content.backgroundColor = CuColor.colors.v2_SeparatorColor
        }
    }
    func setupLayout(){
        tableView.snp.makeConstraints{ (make) -> Void in
            make.top.right.left.bottom.equalTo(self.view);
        }
    }
    func clickPersonInfo(){
        let vc = PersonInfoViewController()
        print("main person click !")
//        CuClient.sharedInstance.centerViewController?.present(vc, animated: true, completion: nil)
        self.present(vc, animated: true, completion : nil)
        //       CuClient.sharedInstance.centerViewController?.navigationController?.pushViewController(vc, animated: true)
    }
}


//MARK: - TableViewDataSource  委托方法实现
extension HomeViewController:UITableViewDataSource,UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections.
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if 1 == indexPath.section {
            return 148
        }else if 0 == indexPath.section {
            return 132
        }else if 2 == indexPath.section {
            return 180
        }
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if 0 == indexPath.section {
//            let cell = getCell(tableView, cell: LeftUserHeadCell.self, indexPath: indexPath);
            let cell = getCell(tableView, cell: ScrollViewCell.self, indexPath: indexPath);
            return cell ;
        }else if 1 == indexPath.section {
            let cell = getCell(tableView, cell: BinInfoViewCell.self, indexPath: indexPath);
//            let cell = getCell(tableView, cell: HomeTableViewCell.self, indexPath: indexPath);
            cell.bind();
            return cell;
//        } else  if 2 == indexPath.section{
////            let cell = getCell(tableView, cell: HomeTableViewRecordsCell.self, indexPath: indexPath);
//            let cell = getCell(tableView, cell: RecordsCell.self, indexPath: indexPath);
//            cell.bind(index: indexPath.row+1)
//            return cell
        }  else if 2 == indexPath.section{
            let cell = getCell(tableView, cell: MenuViewCell.self, indexPath: indexPath)
            return cell;
        }
        return  UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                if !CuUser.sharedInstance.isLogin {
                    let loginViewController = LoginViewController()
                    self.present(loginViewController, animated: true, completion: nil);
                }else{
                    print("已经登录,user:\(String(describing: CuUser.sharedInstance.username))")
//                    memberViewController.username = CuUser.sharedInstance.username
//                    CuClient.sharedInstance.centerNavigation?.pushViewController(memberViewController, animated: true)
//                    CuClient.sharedInstance.drawerController?.closeDrawer(animated: true, completion: nil)
                }
            }
        }else if indexPath.section == 2 {
                    let cell = tableView.cellForRow(at: indexPath) as! MenuViewCell
                    cell.myInfoView?.button?.addTarget(self, action: #selector(clickPersonInfo), for: .touchUpInside)
//        }else if indexPath.section == 2 {
//                if indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 0{
//                    let cell = tableView.cellForRow(at: indexPath) as! FoldingCell
//                    
//                    var duration = 0.0
//                    if itemHeight[indexPath.row] == closeHeight { // open cell
//                        itemHeight[indexPath.row] = openHeight
//                        cell.unfold(true, animated: true, completion: nil)
//                        duration = 0.5
//                    } else {// close cell
//                        itemHeight[indexPath.row] = closeHeight
//                        cell.unfold(false, animated: true, completion: nil)
//                        duration = 1.1
//                    }
//                    
//                    UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
//                        tableView.beginUpdates()
//                        tableView.endUpdates()
//                    }, completion: nil)
////                    
////                let detailViewController = DetailCheckViewController()
////                self.navigationController?.pushViewController(detailViewController, animated: true)
//            }
        }
    }
    
}
